package util;

/**
 * @author rpitts@gmu.edu
 */
import java.io.*;
import java.sql.*;
import java.util.Calendar;

public class SimpleLog {

    File file;
    RandomAccessFile output;
    Timestamp theTime;


    public SimpleLog (String fileName) throws IOException  {
         super();

         /* Setup the Log File */
         file = new File(fileName);
         if(file.exists()){
        	 file.delete();
         }
         file.createNewFile();
         output = new RandomAccessFile(fileName,"rw");
         if (file.length() > 0) output.seek(file.length()); // if append, advance to end of file

         /* Log the initialization of this log file */
         writeLine("");
         writeLine("Log File " + fileName + " Initialized.");
         writeLine("");
    }

    /* Return an SQL style date string */
    private String timeStamp () {
        return theTime.toString();
    }

    /* Generate a time-stamped log-entry from input String */
    public synchronized void writeLine (String logMessage) {
        if(output.getChannel().isOpen()){
	    	/* Setup a time object so log entries can be time stamped */
	        theTime = new Timestamp(Calendar.getInstance().getTime().getTime());
	
	        try {
	    		output.writeBytes("[" + timeStamp() + "] " + logMessage + "\n");
	    	}
	    	catch (Exception e) {
	    		System.out.print("Error writing log: ");
	    		System.out.println(e);
	    	}
        }
    }
    
    public synchronized void close() throws IOException{
    	output.close();
    }

}
